package cn.car91.activity;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.Notification;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewFlipper;
import cn.car91.R;
import cn.car91.bean.User;
import cn.car91.http.HttpHandler;
import cn.car91.service.UpdateService;
import cn.car91.utils.Car91JsonUtil;
import cn.car91.utils.MobileUtils;
import cn.car91.view.PageControlView;

import com.baidu.android.pushservice.CustomPushNotificationBuilder;
import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.baidu.navisdk.BaiduNaviManager;
import com.baidu.push.Utils;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;

public class SplashActivity extends BaseActivity implements OnGestureListener {
    @ViewInject(R.id.viewFlipper)
    ViewFlipper viewFlipper;

    Handler handler = new Handler();
    GestureDetector detector = new GestureDetector(this);

    PageControlView pageControlView;
    TextView startBtn;

    Animation leftInAnimation;
    Animation leftOutAnimation;
    Animation rightInAnimation;
    Animation rightOutAnimation;

    int splash_count = 0;
    //int loop = 3000;//3s

    DbUtils dbUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        setContentView(R.layout.activity_splash);
        super.onCreate(savedInstanceState);

        //createSign();
        
        SharedPreferences setting = getSharedPreferences("Car91", 0);
        //setting.edit().putString("versionFirst", "").commit();
        String user_first = setting.getString("versionFirst", "");
        String version = MobileUtils.getVersionInfo(SplashActivity.this);
        //user_first = "";
        
    	initSomeData();
        if (!version.equals(user_first)) {
            setting.edit().putString("versionFirst", version).commit();
            pageControlView = (PageControlView) findViewById(R.id.pageControlView);
            startBtn = (TextView) findViewById(R.id.app_start_btn);
            startBtn.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					toMain();
				}
			});

            viewFlipper.addView(getImageView(R.drawable.splash_1));
            viewFlipper.addView(getImageView(R.drawable.splash_2));
            viewFlipper.addView(getImageView(R.drawable.splash_3));
            splash_count = 3;

            leftInAnimation = AnimationUtils.loadAnimation(this, R.animator.new_dync_in_from_right);
            leftOutAnimation = AnimationUtils.loadAnimation(this, R.animator.new_dync_out_to_left);
            rightInAnimation = AnimationUtils.loadAnimation(this, R.animator.new_dync_in_from_left);
            rightOutAnimation = AnimationUtils.loadAnimation(this, R.animator.new_dync_out_to_right);
            
            pageControlView.bindViewFlipper(viewFlipper);
            
            //handler.postDelayed(updateThread, loop);
        } else {
            //setting.edit().putBoolean("isFIRST", true).commit();
        	viewFlipper.addView(getImageView(R.drawable.launch));
        	handler.postDelayed(new Runnable() {
				@Override
				public void run() {
					toMain();
				}
			}, 2000);
        }
    }

    RequestCallBack callBackUser = new RequestCallBack() {

        @Override
        public void onFailure(HttpException arg0, String arg1) {
            // TODO Auto-generated method stub
            getCar91Application().setUser(null);
            List<String> tags = new ArrayList<String>();
            tags.add("visitor");
            PushManager.setTags(SplashActivity.this, tags);
        }

        @Override
        public void onSuccess(ResponseInfo arg0) {
            // TODO Auto-generated method stub
            User user = (User) Car91JsonUtil.getDTO(arg0.result.toString(), User.class);
            Intent intent = new Intent();
            intent.setAction(UserLoginActivity.action);
            try {
                if (user.getState().equals(0)) {
                    getCar91Application().setUser(user);
                    intent.putExtra("loginStatus", true);
                } else {
                    getCar91Application().setUser(null);
                    intent.putExtra("loginStatus", false);
                }
            } catch (Exception e) {
                getCar91Application().setUser(null);
                intent.putExtra("loginStatus", false);
            }
            sendBroadcast(intent);
        }
    };

    private void initSomeData(){
    	startService(new Intent(this, UpdateService.class));

        PushManager.startWork(getApplicationContext(),
                PushConstants.LOGIN_TYPE_API_KEY,
                Utils.getMetaValue(SplashActivity.this, "com.baidu.push.api_key"));
        CustomPushNotificationBuilder cBuilder = new CustomPushNotificationBuilder(
                this, R.layout.notification_custom_builder,
                R.id.notification_icon,
                R.id.notification_title,
                R.id.notification_text);
        cBuilder.setNotificationFlags(Notification.FLAG_AUTO_CANCEL);
        cBuilder.setNotificationDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
        cBuilder.setStatusbarIcon(this.getApplicationInfo().icon);
        cBuilder.setLayoutDrawable(R.drawable.ico_launcher);
        PushManager.setNotificationBuilder(this, 100, cBuilder);
        
        User user = getCar91Application().getUser();
        if (user != null) {
            HttpHandler.httpHandler.getUserBasic(user.getId(), callBackUser);
        }

        initSomeConfigs();
    }
    
    private void toMain() {
        Intent intent = new Intent();
        intent.setClass(SplashActivity.this, MainFragmentActivity.class);
        startActivity(intent);
        finish();
    }

    /*Runnable updateThread = new Runnable() {
        public void run() {
            if (viewFlipper.getDisplayedChild() < splash_count - 1) {
                myAnimate();
                handler.postDelayed(updateThread, loop);
            } else {
                handler.removeCallbacks(updateThread);

                toMain();
            }
        }
    };*/

    private ImageView getImageView(int id) {
        ImageView imageView = new ImageView(this);
        imageView.setImageResource(id);
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        imageView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        return imageView;
    }

    /*private void myAnimate() {
        handler.removeCallbacks(updateThread);
        handler.postDelayed(updateThread, loop);
        pageControlView.bindViewFlipper(viewFlipper);
    }*/

    private void initSomeConfigs() {
        HttpHandler.httpHandler.initAppConfig(new RequestCallBack() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {

            }

            @Override
            public void onSuccess(ResponseInfo arg0) {
                String xmls = arg0.result.toString();
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                try {
                    DocumentBuilder builder = factory.newDocumentBuilder();
                    ByteArrayInputStream inStream = new ByteArrayInputStream(xmls.getBytes());
                    Document dom = builder.parse(inStream);

                    Element root = dom.getDocumentElement();
                    NodeList xmlConfig = root.getChildNodes();
                    Map<String, String> onlineConfig = new HashMap<String, String>();
                    for (int i = 0; i < xmlConfig.getLength(); i++) {
                        Node node = xmlConfig.item(i);
                        try {
                            onlineConfig.put(node.getNodeName(), node.getTextContent());
                        } catch (Exception e) {
                        }
                    }
                    getCar91Application().setConfigsMap(onlineConfig);
                    inStream.close();
                } catch (Exception e) {
                    Log.e("xmlException", e.toString());
                }
            }
        });
    }

    @Override
    public boolean onDown(MotionEvent arg0) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean onFling(MotionEvent arg0, MotionEvent arg1, float arg2,
                           float arg3) {
        if (arg0.getX() - arg1.getX() > 120) {
            if (viewFlipper.getDisplayedChild() < splash_count - 1) {
            	viewFlipper.setInAnimation(leftInAnimation);
                viewFlipper.setOutAnimation(leftOutAnimation);
            	viewFlipper.showNext();
            	if(viewFlipper.getDisplayedChild()==splash_count - 1){
            		pageControlView.setVisibility(View.GONE);
            		startBtn.setVisibility(View.VISIBLE);
            	}
            	pageControlView.bindViewFlipper(viewFlipper);
                return true;
            } else {
                //handler.removeCallbacks(updateThread);
                toMain();
                return false;
            }
        } else if (arg0.getX() - arg1.getX() < -120) {
        	if(viewFlipper.getDisplayedChild()!=0){
        		viewFlipper.setInAnimation(rightInAnimation);
                viewFlipper.setOutAnimation(rightOutAnimation);
        		viewFlipper.showPrevious();
        		if(viewFlipper.getDisplayedChild() < splash_count - 1){
            		startBtn.setVisibility(View.GONE);
        			pageControlView.setVisibility(View.VISIBLE);
        		}
        		pageControlView.bindViewFlipper(viewFlipper);
                return true;
        	}
        }
        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        return this.detector.onTouchEvent(event);
    }

    @Override
    public void onLongPress(MotionEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2,
                            float arg3) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void onShowPress(MotionEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean onSingleTapUp(MotionEvent arg0) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    protected void onDestroy() {
        BaiduNaviManager.getInstance().initEngine(this, MobileUtils.getSdcardDir(), null, null);
        super.onDestroy();
    }
    
    /*private void createSign(){
    	String carpai = "川AQ23L8";
    	String carcode = "013405";
    	String city = "成都";
    	String mac = getDeviceMac(this);
    	String data = "carnumber" + carpai + "carcode" + carcode + "cardrivenumber" + "000000" + "mac" + mac + "userid" + "-1" + "city" + city;
        String time = GetCurTime();
        String token = getTokenKey("a1b2c3n451", data, time);
        LogUtils.e("token="+token);
        
        Car91HttpUtil httpUtil = new Car91HttpUtil(this);
        RequestParams params = new RequestParams();
        params.addBodyParameter("carnumber", URLEncoder.encode(carpai));
        params.addBodyParameter("carcode", carcode);
        params.addBodyParameter("cardrivenumber", "000000");
        params.addBodyParameter("mac", mac);
        params.addBodyParameter("userid", "-1");
        params.addBodyParameter("city", URLEncoder.encode(city));
        params.addBodyParameter("sign", token);
        params.addBodyParameter("time", time);
        httpUtil.AsyncHttp("http://test.btbo.com/api/WeizhangPay/RealtimeWeizhang.aspx", params, new RequestCallBack() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				LogUtils.e("error="+arg1);
			}

			@Override
			public void onSuccess(ResponseInfo arg0) {
				LogUtils.e("response="+arg0.result.toString());
			}
		}, HttpMethod.POST);
    }
    
    private String GetCurTime() {
        String ret = System.currentTimeMillis() + "";
        LogUtils.e("time="+ret);
        return ret;
    }
    
    private String getTokenKey(String key, String data, String time) {
        try {
            byte[] data1 = Base64.encode(data.getBytes(), 0x2);
            String data2 = new String(data1, "UTF-8");
            String data3 = key + time + data2;
            byte[] data4 = Base64.encode(data3.getBytes(), 0x2);
            String data5 = new String(data4, "UTF-8");
            return data5;
        } catch(Exception e) {
            LogUtils.e("create token is error");
        }
        return "";
    }
    
    private String getDeviceMac(Context context) {
        WifiManager wifi = (WifiManager)getSystemService("wifi");
        WifiInfo info = wifi.getConnectionInfo();
        String mCode = info.getMacAddress();
        if(mCode == null) {
            return "";
        }
        return mCode;
    }*/
}
